package service;

import model.Application;
import model.ReviewRecord;
import model.User;
import Repository.ApplicationRepository;
import Repository.ReviewRecordRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ApplicationService {

    @Autowired
    private ApplicationRepository applicationRepository;
    @Autowired
    private ReviewRecordRepository reviewRecordRepository;

    public Map<String, Object> submitApplication(User applicant, String content) {
        Map<String, Object> response = new HashMap<>();
        Application application = new Application(applicant, content);
        applicationRepository.save(application);
        response.put("success", true);
        response.put("message", "申报成功！等待审核。");
        return response;
    }

    public List<Application> getApplicationsByStatus(int status) {
        return applicationRepository.findByStatus(status);
    }

    public Map<String, Object> conductReview(User reviewer, Application application, int reviewLevel, boolean isApproved, String comment) {
        Map<String, Object> response = new HashMap<>();
        int newStatus = getNextStatus(application.getStatus(), isApproved, reviewLevel);
        application.setStatus(newStatus);
        applicationRepository.save(application);
        ReviewRecord record = new ReviewRecord(application, reviewer, reviewLevel, isApproved, comment);
        reviewRecordRepository.save(record);
        response.put("success", true);
        response.put("message", "审核记录保存成功。");
        return response;
    }

    private int getNextStatus(int currentStatus, boolean isApproved, int reviewLevel) {
        if (!isApproved) {
            return -1;
        }
        switch (reviewLevel) {
            case 1:
                return 1;
            case 2:
                return 2;
            case 3:
                return 3;
            default:
                return currentStatus;
        }
    }
}